
//
//  LXShopCartController.m
//  LvXi_newVersion
//
//  Created by 王敏 on 16/8/16.
//  Copyright © 2016年 SJT. All rights reserved.
//

#import "LXShopCartController.h"

#import "SubmitOrderController.h"

#import "LXShoppingCarCommodityViewCell.h"

#import "ShopCartBottomToolView.h"

#import "ShopCartSectionHeader.h"

#import "LCTabBarController.h"

@interface LXShopCartController ()<UITableViewDelegate,UITableViewDataSource,ShopCartSectionHeaderDelegate,MGSwipeTableCellDelegate,LXShoppingCarCommodityViewCellDelegate,ShopCartManagerDelegate>{
    CGPoint _tableViewCurrentOffset;
}


@property(nonatomic,strong)UITableView * tableView;

@property(nonatomic,strong)ShopCartBottomToolView * bottomTool;

@property(nonatomic,strong)NSMutableArray * goodsArray;

@end

@implementation LXShopCartController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.goodsArray = [NSMutableArray array];
    [ShopCartManager getAllProductComplete:^(NSArray *datas) {
         [self.goodsArray removeAllObjects];
         [[LXDataManager manager] listFocusProductWithComplete:^(BOOL success, id res) {
             [self.goodsArray addObjectsFromArray:datas];
             for (Product * sp in self.goodsArray) {
                 sp.haveFocus = NO;
                 for (Product * fp in res) {
                     if([sp.product_id isEqualToString:fp.product_id]){
                         sp.haveFocus = YES;
                         break;
                     }
                 }
             }
             [self.tableView reloadData];
         }];
    }];

    [self xw_registerBackInteractiveTransitionWithDirection:XWInteractiveTransitionGestureDirectionRight transitonBlock:^(CGPoint startPoint) {
        [self.navigationController popViewControllerAnimated:YES];
    } edgeSpacing:50];
    [ShopCartManager setDelegate:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setUpNavi];

     if (LoginState){
        [self.view addSubview:self.tableView];
        [self.view addSubview:self.bottomTool];
         self.bottomTool.totalPrice = [ShopCartManager calculateSelectedPrice];
     }else{
         LXLoginViewController * loginVC = [[LXLoginViewController alloc] init];
         loginVC.closeCallBack = ^(){
             [self.navigationController popToRootViewControllerAnimated:YES];
             [self.navigationController.tabBarController setSelectedIndex:0];
         };
         [self presentViewController:loginVC animated:YES completion:nil];
     }
    LCTabBarController * tbvc =  (LCTabBarController *)self.navigationController.tabBarController;
    
    if(self.navigationController.viewControllers.count == 1){
        tbvc.tabBarHidden = NO;
    }else{
        tbvc.tabBarHidden = YES;
    }
    self.tableView.contentInset = (UIEdgeInsets){0,0,0,0};
    
    
    if(tbvc.tabBarHidden){
        self.bottomTool.y = ScreenHeight - self.bottomTool.height - 64;
    }else{
        self.bottomTool.y = ScreenHeight - self.bottomTool.height-50 - 64;
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationItem.title= @"";
}

-(void)setUpNavi{
    [super setUpNavi];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"购物车";
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}



-(UITableView*)tableView{
    if(_tableView == nil){
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _tableView;
}


#pragma mark - 底部工具栏
-(ShopCartBottomToolView*)bottomTool{
    WeakSelf(ws);
    if(_bottomTool == nil){
        static CGFloat const toolViewHeight = 44;
        _bottomTool  = [[ShopCartBottomToolView alloc] initWithFrame:CGRectMake(0, ScreenSize.height-toolViewHeight-49, ScreenSize.width, toolViewHeight)];
        _bottomTool.handle = ^(UIButton* button){
            if([ShopCartManager shareManager].selectedProduct.count==0){
                [ws.view alertWithTitle:@"" mesege:@"您还没有选择商品" buttons:@[@"知道了"] handle:^(NSInteger buttonIndex) {
                    
                }];
            }else{
                SubmitOrderController * vc= [[SubmitOrderController alloc] init];
                [ws.navigationController pushViewController:vc animated:YES];
            }
        };
        _bottomTool.allSelected = ^(UIButton * button)
        {
            if(button.selected){
              [[ShopCartManager shareManager].selectedProduct removeAllObjects];
                [[ShopCartManager shareManager].selectedProduct addObjectsFromArray:ws.goodsArray];
                ws.bottomTool.totalPrice =[ShopCartManager calculateSelectedPrice];
            }else{
                [[ShopCartManager shareManager].selectedProduct removeAllObjects];
                ws.bottomTool.totalPrice = 0.00;
            }
            [ws.tableView reloadData];
        };
    }
    return _bottomTool;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.goodsArray.count;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LXShoppingCarCommodityViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"aaaaaa"];
    if(!cell){
        cell = [[LXShoppingCarCommodityViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"aaaaaa"];
    }
    if(self.goodsArray.count!=0){
        cell.product = self.goodsArray[indexPath.section];
    }
    cell.editing = YES;
    [self addCellHeight:cell.cellHeight indexPath:indexPath];
    cell.delegate = self;
    if([[ShopCartManager shareManager].selectedProduct indexOfObject:cell.product] == NSNotFound){
        cell.selectedBtn.selected = NO;
    }else{
        cell.selectedBtn.selected = YES;
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self cellHeightForIndexPath:indexPath];
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    ShopCartSectionHeader * header = [[ShopCartSectionHeader alloc] initWithFrame:CGRectMake(0, 0,ScreenWidth, 50)];
    header.section = section;
    header.delegate = self;
    if([[ShopCartManager shareManager].selectedProduct indexOfObject:self.goodsArray[section]]==NSNotFound){
        header.selectedButton.selected = NO;
    }else{
        header.selectedButton.selected = YES;
    }
    return header;
}


#pragma mark - 商品cell代理

-(void)LXShoppingCarCommodityViewCell:(LXShoppingCarCommodityViewCell *)cell didClickAddSteper:(LXSteper *)steper{
    [ShopCartManager addProduct:cell.product complete:^(NSArray *datas) {
        steper.steperValue+=1;
        [self.goodsArray removeAllObjects];
        [self.goodsArray addObjectsFromArray:datas];
        [self.tableView reloadData];
    }];
}

-(void)LXShoppingCarCommodityViewCell:(LXShoppingCarCommodityViewCell *)cell didClickReduceSteper:(LXSteper *)steper{
    [ShopCartManager removeProduct:cell.product complete:^(NSArray *datas) {
        steper.steperValue = cell.product.numberInShopCart;
        [self.goodsArray removeAllObjects];
        [self.goodsArray addObjectsFromArray:datas];
        [self.tableView reloadData];
    }];
}

-(void)LXShoppingCarCommodityViewCell:(LXShoppingCarCommodityViewCell *)cell product:(Product *)product isSelected:(BOOL)isSelected{
    if(isSelected){
        [ShopCartManager addSelectedProduct:product];
    }else{
        [ShopCartManager deleteSelectedProduct:product];
    }
}

#pragma mark - cell侧滑代理
-(BOOL) swipeTableCell:(MGSwipeTableCell*)cell canSwipe:(MGSwipeDirection) direction{
    return YES;
}
-(NSArray*)swipeTableCell:(MGSwipeTableCell *)cell swipeButtonsForDirection:(MGSwipeDirection)direction swipeSettings:(MGSwipeSettings *)swipeSettings expansionSettings:(MGSwipeExpansionSettings *)expansionSettings{
    LXShoppingCarCommodityViewCell * cel = (LXShoppingCarCommodityViewCell *)cell;
    if(direction == MGSwipeDirectionRightToLeft){
        MGSwipeButton * btn1 = [[MGSwipeButton alloc] initWithFrame:CGRectMake(0, 0, ShopCart_height(68), cell.cellHeight)];
        btn1.backgroundColor = HexColor(@"#AAAAAA");
        btn1.titleLabel.font = [UIFont systemFontOfSize:10];
        [btn1 setImage:[UIImage imageNamed:@"like_2_white"] forState:UIControlStateNormal];
        [btn1 setTitle:cel.product.haveFocus?@"移出关注":@"移入关注" forState:UIControlStateNormal];
        btn1.imageEdgeInsets = UIEdgeInsetsMake(ShopCart_height(29),ShopCart_width(18), ShopCart_height(50), ShopCart_width(18));
        CGSize titleSize = [btn1.currentTitle sizeInAre:MaxSize font:btn1.titleLabel.font];
        btn1.titleEdgeInsets = UIEdgeInsetsMake(ShopCart_height(80),ShopCart_width(-(titleSize.width-8)), ShopCart_height(50), ShopCart_width(0));
        
        MGSwipeButton * btn2 = [[MGSwipeButton alloc] initWithFrame:CGRectMake(0, 0, ShopCart_width(68), cell.cellHeight)];
        btn2.titleLabel.font = [UIFont systemFontOfSize:10];
        btn2.backgroundColor = HexColor(@"#F0A228");
        [btn2 setImage:[UIImage imageNamed:@"delete_1_white"] forState:UIControlStateNormal];
        [btn2 setTitle:@"删除" forState:UIControlStateNormal];
        
        
        btn2.imageEdgeInsets = UIEdgeInsetsMake(ShopCart_height(29),ShopCart_width(18), ShopCart_height(50), ShopCart_width(18));
        titleSize = [btn2.currentTitle sizeInAre:MaxSize font:btn2.titleLabel.font];
        btn2.titleEdgeInsets = UIEdgeInsetsMake(ShopCart_height(80),ShopCart_width(-(titleSize.width+9)), ShopCart_height(50), ShopCart_width(0));

        if([btn1.currentTitle isEqualToString:@"移入关注"]){
            btn1.callback = ^(MGSwipeTableCell * sender){
                LXShoppingCarCommodityViewCell * cell = (LXShoppingCarCommodityViewCell *)sender;
                [[LXDataManager manager] addFocusProduct:cell.product complete:^(BOOL success, id res) {
                    if(success){
                        if([res[@"data"][@"error"] isEqualToString:@"关注成功"]){
                            cell.product.haveFocus = YES;
                        }
                        [SVProgressHUD showSuccessWithStatus:res[@"data"][@"error"]];
                        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [SVProgressHUD dismiss];
                            [self.tableView reloadData];
                        });
                    }
                }];
                
                return YES;
            };
 
        }else{
            btn1.callback = ^(MGSwipeTableCell * sender){
                LXShoppingCarCommodityViewCell * cell = (LXShoppingCarCommodityViewCell *)sender;
                [[LXDataManager manager] delFocusProduct:cell.product complete:^(BOOL success, id res) {
                    if(success){
                        if([res[@"data"][@"error"] isEqualToString:@"删除成功"]){
                            cell.product.haveFocus = NO;
                        }
                        [SVProgressHUD showSuccessWithStatus:res[@"data"][@"error"]];
                        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [SVProgressHUD dismiss];
                            [self.tableView reloadData];
                        });
                    }
                }];
                return YES;
            };
        }
        
        btn2.callback = ^(MGSwipeTableCell * sender){
            LXShoppingCarCommodityViewCell * cell = (LXShoppingCarCommodityViewCell*)sender;
            
            [ShopCartManager removeAllProduct:cell.product complete:^(NSArray *datas) {
                [self.goodsArray removeAllObjects];
                [self.goodsArray addObjectsFromArray:datas];
                [self.tableView reloadData];
            }];
            return YES;
        };
        return @[btn2,btn1];
    }
    return nil;
}

#pragma mark - 分组头部视图代理方法
-(void)selectedButtonClickWithButton:(UIButton *)button Section:(NSInteger)section{
    if(button.selected){
        [ShopCartManager addSelectedProduct:self.goodsArray[section]];
    }else{
        [ShopCartManager deleteSelectedProduct:self.goodsArray[section]];
    }
    
    [self.tableView reloadSections:[[NSIndexSet alloc] initWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}


-(void)ShopCartManager:(ShopCartManager *)manager didUpDateSelectedProductPrice:(CGFloat)price{
    self.bottomTool.totalPrice = price;
}
@end
